package com.arsn.myf.common.excel;

import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.*;

import java.util.List;

/**
 * 修改单元格格式为文本格式
 * @author zhongrj
 * @since 2021-9-26
 */
public class RowWriteHandler implements CellWriteHandler {

	public static CellStyle cellStyle;

	/**
	 * 设置全局变量，防止  cellStyle 创建过多报错 2021-12-16 zrj
	 * The maximum number of cell styles was exceeded. You can define up to 64000styles in a .xlsx workbook
	 * @param cellStyle
	 */
	public static void setCellStyle(CellStyle cellStyle) {
		RowWriteHandler.cellStyle = cellStyle;
	}

	@Override
	public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Head head, Integer integer, Integer integer1, Boolean aBoolean) {

	}

	@Override
	public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell, Head head, Integer integer, Boolean aBoolean) {
		//设置单元格格式为文本
		Workbook workbook = writeSheetHolder.getSheet().getWorkbook();
		//自定义样式不为空时,重复利用
		if(null==cellStyle){
			cellStyle = workbook.createCellStyle();
			setCellStyle(cellStyle);
		}
		DataFormat dataFormat = workbook.createDataFormat();
		cellStyle.setDataFormat(dataFormat.getFormat("@"));
		cell.setCellStyle(cellStyle);
	}

	//@Override 加上会报错
	public void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, CellData cellData, Cell cell, Head head, Integer integer, Boolean aBoolean) {

	}

	@Override
	public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<CellData> list, Cell cell, Head head, Integer integer, Boolean aBoolean) {

	}
}
